package com.youdoneed.community.group.service;

import java.math.BigDecimal;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.application.ResultMessage;
import com.youdoneed.community.common.utils.StringUUIdUtil;
import com.youdoneed.community.forum.dao.ForumnoticeMapper;
import com.youdoneed.community.forum.entity.Forumnotice;
import com.youdoneed.community.forum.service.ForumServciceStatic;
import com.youdoneed.community.group.dao.ForumgroupMapper;
import com.youdoneed.community.group.dao.ForumgroupinvitationrecordMapper;
import com.youdoneed.community.group.dao.ForumuserapplyjoingrouprecordMapper;
import com.youdoneed.community.group.dao.ForumuserinforumgroupMapper;
import com.youdoneed.community.group.dao.GroupnoticeMapper;
import com.youdoneed.community.group.entity.Forumgroup;
import com.youdoneed.community.group.entity.Forumgroupinvitationrecord;
import com.youdoneed.community.group.entity.Forumuserapplyjoingrouprecord;
import com.youdoneed.community.group.entity.Forumuserinforumgroup;
import com.youdoneed.community.group.entity.Groupnotice;
import com.youdoneed.community.group.vo.BatchVo;
import com.youdoneed.community.group.vo.ForumInUserGroupVo;
import com.youdoneed.community.group.vo.ForumgroupInUserVo;
import com.youdoneed.community.group.vo.HuanxinJson;
import com.youdoneed.friends.feign.FriendsClient;
import com.youdoneed.user.feign.UserFeignClient;
import com.youdoneed.user.model.FocusRegion;
import com.youdoneed.user.model.User;

@Service
public class ForumgroupService {
    private final Logger logger = LoggerFactory.getLogger(ForumgroupService.class);
    //群默认最大人数
    private static int maxusers = 2000;
    //群隐私(true :公开 ,false :非公开)
    private boolean privacy;
    //进群是否需要群主或者管理员通过(true :需要 ,false :不需要)
    private boolean members_only;

    private String privacys = "公开";

    private static final Gson GSON = new Gson();
    @Autowired
    ForumgroupMapper forumgroupMapper;
    @Autowired
    GroupnoticeMapper groupnoticeMapper;

    @Autowired
    ForumuserinforumgroupMapper forumuserinforumgroupMapper;

    @Autowired
    ForumuserapplyjoingrouprecordMapper forumuserapplyjoingrouprecordMapper;

    @Autowired
    ForumgroupinvitationrecordMapper forumgroupinvitationrecordMapper;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    FriendsClient friendsClient;

    @Autowired
    ForumnoticeMapper forumnoticeMapper;

    /**
     * 创建小组
     *
     * @param forumgroup
     * @param userId
     * @author lixs
     * @Date 2017.7.28
     */
    @Transactional
    public String saveForumGroup(Forumgroup forumgroup, List<String> userId) {
        logger.info("saveForumGroup!");

        if (userId == null) {
            throw new AppException("userId参数为空");
        }
        if (userId.size() < 2) {
            throw new AppException("邀请人数必须超过两人才能建组哦");
        }
        //群组信息判空
        groupDetailJudgement(forumgroup);

        if (forumgroup.getPrivacySetting() == null) {
            throw new AppException("群组隐私不能为空");
        }

        //判断邀请的用户中是否包含群主id
        for (String userid : userId) {
            if (userid.equals(forumgroup.getLeaderUserId())) {
                throw new AppException("邀请的好友不能包含群主自己");
            }
        }

        if (forumgroup.getPrivacySetting() == ForumgroupStatic.privacy_public) {
            privacy = true;
            members_only = false;
        } else {
            privacy = false;
            members_only = true;
        }
        logger.info("privacy" + privacy);
        logger.info("members_only" + members_only);

        //调用环信接口，创建小组
        HuanxinJson huanxinJson = createHuanxinGroup(forumgroup, userId, privacy, members_only);

        //创建用户小组
        String groupIntroduction = "这是一个分享快乐的小组";
        Forumgroup forumgroupNew = createGroup(forumgroup, userId, huanxinJson, groupIntroduction,
                ForumgroupStatic.forum_group_for_other, ForumgroupStatic.forum_group_type_for_user,
                forumgroup.getPrivacySetting());

        //默认将群主邀请的用户存入邀请的记录中
        for (int i = 0; i < userId.size(); i++) {
            saveGroupInvitationRecord(forumgroupNew, userId.get(i));
        }

        //保存邀请通知
        for (int i = 0; i < userId.size(); i++) {
            saveForumnotice(forumgroupNew, userId.get(i));
        }

        //创建小组与组员的关联
        for (int i = 0; i < userId.size(); i++) {
            saveGroupAndLeaderRel(forumgroupNew, userId.get(i));
        }

        //保存群主与小组的关联关系
        saveGroupAndLeaderRel(forumgroupNew, forumgroupNew.getLeaderUserId());
        return forumgroupNew.getForumGroupId();


    }

    /**
     * 创建本地群组
     *
     * @param forumgroup
     * @param userId
     * @param huanxinJson
     * @param groupIntroduction
     * @param groupStyle
     * @param groupType
     * @param groupPrivacy
     * @author lixs
     * @Date 2017.12.13
     */
    @Transactional
    public Forumgroup createGroup(Forumgroup forumgroup, List<String> userId, HuanxinJson huanxinJson, String groupIntroduction, String groupStyle, String groupType, Integer groupPrivacy) {
        Forumgroup forumgroupNew = new Forumgroup();
        forumgroupNew.setCreateDate(new Date());
        if (null == userId) {
            forumgroupNew.setMemberCount(1);
        } else {
            forumgroupNew.setMemberCount(userId.size() + 1);
        }
        forumgroupNew.setHeadUrl(forumgroup.getHeadUrl());
        forumgroupNew.setForumGroupId(StringUUIdUtil.getUUID());
        forumgroupNew.setPrivacySetting(groupPrivacy);
        forumgroupNew.setGroupName(forumgroup.getGroupName());
        forumgroupNew.setLeaderUserId(forumgroup.getLeaderUserId());
        //小组创建者的昵称和头像是动态从用户表中获取。
        forumgroupNew.setLeaderUserNickname(userFeignClient.getUser(forumgroup.getLeaderUserId()).getData().getName());
        forumgroupNew.setLeaderUserHeadUrl(userFeignClient.getUser(forumgroup.getLeaderUserId()).getData().getImageUrl());
        forumgroupNew.setLongitude(exchange(forumgroup.getLongitude()));
        forumgroupNew.setLatitude(exchange(forumgroup.getLatitude()));
        forumgroupNew.setGroupIntroduction(groupIntroduction);
        forumgroupNew.setGroupMessageTotal(0);
        forumgroupNew.setHuanxinGroupId(huanxinJson.data.groupid);
        //默认是用户小组
        forumgroupNew.setGroupType(groupType);
        forumgroupNew.setAddress(forumgroup.getAddress());
        //默认群组类型是“其他”
        forumgroupNew.setGroupStyle(groupStyle);
        //没有选定默认的图片
        forumgroupNew.setGroupBackgroundUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/15x0ph5iiwd6wa8s2ta3.png");
        String notice = "创建了" + forumgroup.getGroupName() + "小组";
        forumgroupNew.setGroupNotice(notice);
        forumgroupNew.setCountPeopleToBeAudited(0);
        forumgroupMapper.insertSelective(forumgroupNew);

        createGroupNotice(forumgroupNew, notice);
        return forumgroupNew;
    }


    /**
     * 插入一条动态
     *
     * @param forumgroup
     * @param description
     * @return
     */
    public int createGroupNotice(Forumgroup forumgroup, String description) {
        Groupnotice groupnotice = new Groupnotice();
        groupnotice.setCreateDate(new Date());
        groupnotice.setForumGroupId(forumgroup.getForumGroupId());
        groupnotice.setNoticeDescription(description);
        groupnotice.setNoticeOperatorId(forumgroup.getLeaderUserId());
        groupnotice.setGroupHeadUrl(forumgroup.getHeadUrl());
        groupnotice.setOperatorHead(forumgroup.getLeaderUserHeadUrl());
        groupnotice.setOperatorName(forumgroup.getLeaderUserNickname());

        return groupnoticeMapper.insert(groupnotice);


    }


    /**
     * 在环信后台注册群组信息
     *
     * @param forumgroup
     * @param userId
     * @author lixs
     * @Date 20217.12.13
     */
    public HuanxinJson createHuanxinGroup(Forumgroup forumgroup, List<String> userId, Boolean privacy, Boolean members_only) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        logger.info("创建环信小组");
        resultMap.put("groupname", forumgroup.getGroupName());
        resultMap.put("desc", "这是一个分享快乐的小组!");
        resultMap.put("public", privacy);
        //设置群最大人数（包含群主）
        resultMap.put("maxusers", maxusers);
        resultMap.put("members_only", members_only);
        //allowinvites 是否允许群成员邀请别人加入此群。 true：允许群成员邀请人加入此群
        resultMap.put("allowinvites", true);
        resultMap.put("owner", forumgroup.getLeaderUserId());
        if (null == userId) {
            resultMap.put("members", null);
        } else {
            resultMap.put("members", userId.toArray(new String[userId.size()]));
        }
        ResultMessage message = friendsClient.createGroupUser(resultMap);
        if (!message.isSuccess()){
            throw new AppException(message.getData().toString());
        }
        //解析环信返回的json
        String result = message.getData().toString();
        HuanxinJson huanxinJson = GSON.fromJson(result, HuanxinJson.class);
        return huanxinJson;
    }

    /**
     * 保存群组邀请记录
     *
     * @param forumgroupNew
     * @param userId
     * @author lixs
     * @Date 2017.12.13
     */
    @Transactional
    public void saveGroupInvitationRecord(Forumgroup forumgroupNew, String userId) {
        Forumgroupinvitationrecord forumgroupinvitationrecord = new Forumgroupinvitationrecord();
        forumgroupinvitationrecord.setInviteStatus(ForumgroupStatic.invite_status_agree);
        forumgroupinvitationrecord.setCreateDate(new Date());
        forumgroupinvitationrecord.setGroupId(forumgroupNew.getForumGroupId());
        forumgroupinvitationrecord.setGroupInvitationRecordId(StringUUIdUtil.getUUID());
        forumgroupinvitationrecord.setInvitedUserId(userId);
        forumgroupinvitationrecord.setUserHeadUrl(userFeignClient.getUser(forumgroupNew.getLeaderUserId()).getData().getImageUrl());
        forumgroupinvitationrecord.setUserId(forumgroupNew.getLeaderUserId());
        forumgroupinvitationrecord.setUserNickName(userFeignClient.getUser(forumgroupNew.getLeaderUserId()).getData().getName());
        forumgroupinvitationrecordMapper.insertSelective(forumgroupinvitationrecord);
    }

    /**
     * 保存邀请通知
     *
     * @param forumgroupNew
     * @param userId
     * @author lixs
     * @Date 2017.12.13
     */
    @Transactional
    public void saveForumnotice(Forumgroup forumgroupNew, String userId) {
        Forumnotice forumnotice = new Forumnotice();
        forumnotice.setCreateDate(new Date());
        forumnotice.setForumNoticeId(StringUUIdUtil.getUUID());
        forumnotice.setNoticeType(ForumServciceStatic.gpInvitationNotice);
        forumnotice.setNoticeUserHeadUrl(userFeignClient.getUser(forumgroupNew.getLeaderUserId()).getData().getImageUrl());
        forumnotice.setNoticeUserId(forumgroupNew.getLeaderUserId());
        forumnotice.setReadStatus(Forumnotice.UN_READ);
        forumnotice.setSourceId(forumgroupNew.getForumGroupId());
        forumnotice.setUserId(userId);
        forumnotice.setNoticeUserNickname(userFeignClient.getUser(forumgroupNew.getLeaderUserId()).getData().getName());
        forumnotice.setSourceDesc(forumgroupNew.getGroupName());
        forumnoticeMapper.insertSelective(forumnotice);
    }

    /**
     * 创建群员与小组的关联
     *
     * @param forumgroup
     * @param userId
     * @author lixs
     * @Date 2017.12.13
     */
    @Transactional
    public void saveGroupAndLeaderRel(Forumgroup forumgroupNew, String userId) {
        Forumuserinforumgroup forumuserinforumgroupLeader = new Forumuserinforumgroup();
        forumuserinforumgroupLeader.setUserInForumGroupId(StringUUIdUtil.getUUID());
        forumuserinforumgroupLeader.setCreateDate(new Date());
        forumuserinforumgroupLeader.setForumGroupId(forumgroupNew.getForumGroupId());
        forumuserinforumgroupLeader.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
        forumuserinforumgroupLeader.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
        forumuserinforumgroupLeader.setUserId(userId);
        forumuserinforumgroupMapper.insert(forumuserinforumgroupLeader);
    }

    /**
     * 查找我的小组
     *
     * @param userId
     * @return List<Forumgroup>
     * @author lid
     * @date 2017.6.25
     */
    public List<Forumgroup> getMyGroups(String userId, Integer rows, Integer currentPage) {

        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId参数为空");
        }
        PageHelper.startPage(currentPage, rows);
        List<Forumgroup> forumgroup = forumgroupMapper.getMyGroups(userId, ForumgroupStatic.forum_group_type_for_delete);
        if (forumgroup == null) {
            throw new AppException("您还未加入小组或您加入的小组已解散");
        }
        return forumgroup;
    }

    /**
     * 查找我加入的群组
     *
     * @param userId
     * @return List<Forumgroup>
     */
    @Transactional
    public List<Forumgroup> getMyGroups(String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId参数为空");
        }
        return forumgroupMapper.getMyGroups(userId, ForumgroupStatic.forum_group_type_for_delete);
    }

    /**
     * 查找附近的小组
     *
     * @param longitude
     * @param latitude
     * @return List<ForumInUserGroupVo>
     * @author lixs
     * @date 2017.7.14
     */
    @Transactional
    public List<ForumInUserGroupVo> getNearByGroups(Double userLongitud, Double uerLatitude, Integer distance, String userId, Integer currentPage, Integer rows) {
        if (userLongitud == null) {
            throw new AppException("用户经度不能为空");
        }
        if (uerLatitude == null) {
            throw new AppException("用户纬度不能为空");
        }
        if (distance == null) {
            throw new AppException("用户设置的距离不能为空");
        }

        PageHelper.startPage(currentPage, rows);

        ResultMessage<FocusRegion> focusRegion = userFeignClient.checkedFocusRegion();
        if (null == focusRegion) {
            logger.info("关注区域为空");
            double ratio = Math.cos(uerLatitude * 0.017453292519943295);
            double latitudeDistance = distance * 0.000008998200359928014;

            // 以纬度为标准 纬度换算成等效经度距离
            double longitudeDistance = latitudeDistance / ratio;
            Double minLongitude = userLongitud - longitudeDistance;
            Double maxLongitude = userLongitud + longitudeDistance;
            Double minLatitude = uerLatitude - latitudeDistance;
            Double maxLatitude = uerLatitude + latitudeDistance;
            return forumgroupMapper.selectNearbyGroups(minLongitude, maxLongitude, minLatitude, maxLatitude, userId, userLongitud, uerLatitude, distance, ForumgroupStatic.privacy_public);
        }
        logger.info("关注区域不为空");
        Double latitude = focusRegion.getData().getLatitude();
        Double longitud = focusRegion.getData().getLongitude();

        double ratio = Math.cos(latitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;

        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude = longitud - longitudeDistance;
        Double maxLongitude = longitud + longitudeDistance;
        Double minLatitude = latitude - latitudeDistance;
        Double maxLatitude = latitude + latitudeDistance;
        return forumgroupMapper.selectNearbyGroups(minLongitude, maxLongitude, minLatitude, maxLatitude, userId, userLongitud, uerLatitude, distance, ForumgroupStatic.privacy_public);
    }

    /**
     * 退出小组
     *
     * @param userId
     * @param groupId
     * @return boolean
     * @author lixs
     * @date 2017.7.25
     */
    @Transactional
    public boolean quitGroup(String userId, String groupId) {

        logger.info("退出小组");
        if (!StringUtils.hasText(groupId)) {
            throw new AppException("小组id不能为空");
        }
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户id不能为空");
        }
        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(groupId);
        if (forumgroup == null) {
            throw new AppException("不存在该小组");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已解散");
        }
        //小组创建者退群的话，逻辑删除小组
        if (userId.equals(forumgroup.getLeaderUserId())) {
//			forumgroupMapper.deleteByUserIdAndGroupId(forumgroup.getLeaderUserId(), groupId);
            //逻辑删除小组
            forumgroup.setGroupType(ForumgroupStatic.forum_group_type_for_delete);
            forumgroup.setMemberCount(0);
            forumgroupMapper.updateByPrimaryKeySelective(forumgroup);
            //删除小组与用户的关联记录
            forumuserinforumgroupMapper.deleteByForumgroupId(groupId);

            //调用环信接口：解散群组
            friendsClient.deleteGroup(forumgroup.getHuanxinGroupId());
            logger.info("解散小组");
            return true;
        }

        //普通成员退群，则删去他与小组关联的记录
        Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, groupId);
        if (forumuserinforumgroup == null) {
            throw new AppException("您已不在该小组中");
        }

        //如果是邀请进群，则用户退群时删除用户的邀请记录
        Forumgroupinvitationrecord forumgroupinvitationrecord = forumgroupinvitationrecordMapper.selectByGroupIdAndUserId(userId, groupId);
        if (null != forumgroupinvitationrecord) {
            //删除用户的邀请记录
            forumgroupinvitationrecordMapper.deleteByPrimaryKey(forumgroupinvitationrecord.getGroupInvitationRecordId());
        }

        //如果是通过申请进群，则用户退群时删除用户的申请状态，置为申请被拒绝
        Forumuserapplyjoingrouprecord applyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, groupId);
        if (null != applyjoingrouprecord) {
            applyjoingrouprecord.setApplyStatus(ForumgroupStatic.not_in_group);
            forumuserapplyjoingrouprecordMapper.updateByPrimaryKeySelective(applyjoingrouprecord);
            logger.info("申请记录的状态值为" + applyjoingrouprecord.getApplyStatus());

            //调用环信接口，移除单个群组成员
            friendsClient.deleteGroupUser(forumgroup.getHuanxinGroupId(), userId);
            //删除本地的群组与用户的关联记录
            forumuserinforumgroupMapper.deleteByUserIdAndGroupId(userId, groupId);

            List<Forumuserinforumgroup> forumuserinforumgroupnew = forumuserinforumgroupMapper.selectByGroupId(groupId);
            forumgroup.setMemberCount(forumuserinforumgroupnew.size());
            forumgroupMapper.updateByPrimaryKey(forumgroup);
            return true;
        }

        //调用环信接口，移除单个群组成员
        friendsClient.deleteGroupUser(forumgroup.getHuanxinGroupId(), userId);
        //删除本地的群组与用户的关联记录

        forumuserinforumgroupMapper.deleteByUserIdAndGroupId(userId, groupId);

        List<Forumuserinforumgroup> forumuserinforumgroupnew = forumuserinforumgroupMapper.selectByGroupId(groupId);
        forumgroup.setMemberCount(forumuserinforumgroupnew.size());
        forumgroupMapper.updateByPrimaryKey(forumgroup);
        return true;
    }

    /**
     * 获取小组的成员id
     *
     * @param groupId
     * @return List<String>
     * @author lid
     * @date 2017.6.25
     */
    @Transactional
    public List<String> getMembersInGroup(String groupId) {
        /**
         * lxs
         */
        logger.info("获取小组成员ID");
        if (!StringUtils.hasText(groupId)) {
            throw new AppException("小组id不能为空");
        }
        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(groupId);
        if (forumgroup == null) {
            throw new AppException("小组信息为空");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已被解散");
        }
        //调用环信接口，获取小组成员信息
//		friendsClient.getGroupUsers(forumgroup.getHuanxinGroupId());
        List<Forumuserinforumgroup> forumuserinforumgroup = forumuserinforumgroupMapper.selectByGroupId(groupId);
        List<String> userId = new ArrayList<>();
        for (Forumuserinforumgroup fusergroup : forumuserinforumgroup) {
            userId.add(fusergroup.getUserId());
        }
        return userId;
    }

    /**
     * 小组的设置
     *
     * @param forumgroup
     * @return boolean
     * @author lixs
     * @Date 2017.7.10
     */
    @Transactional
    public int groupPrivacySetting(String forumGroupId, String groupName, String groupIntroduction, Integer privacySetting,
                                   Double longitude, Double latitude, String groupStyle, String address, int noticeType) {
        logger.info("小组的设置");
        if (!StringUtils.hasText(forumGroupId)) {
            throw new AppException("小组id为空");
        }
        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumGroupId);
        if (forumgroup == null) {
            throw new AppException("未查到该小组信息");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已被解散");
        }
        if (groupName.length() > 15) {
            throw new AppException("小组名称长度不能超过15个字符");
        }
        if (groupIntroduction.length() > 200) {
            throw new AppException("小组简介不能超过200个字符");
        }
        String maxUser = String.valueOf(maxusers);
        //调用环信接口：修改小组设置
        friendsClient.modifyGroupDetails(forumgroup.getHuanxinGroupId(), groupName, groupIntroduction, maxUser);

//        "1：修改小组名 ；2：修改简介；3：隐私设置；" +          "4：修改位置"
        String notice = "";
        switch (noticeType) {
            case 1:
                notice = "修改了小组名称";
                break;
            case 2:
                notice = "修改了小组简介";
                break;
            case 3:
                notice = "修改了小组隐私设置";
                break;
            case 4:
                notice = "修改了小组位置";
                break;
            default:
                break;
        }
        createGroupNotice(forumgroup, notice);
        return forumgroupMapper.updateByPrimaryKeyForprivacy(forumGroupId, groupName, groupIntroduction, privacySetting,
                longitude, latitude, groupStyle, address);
    }

    /**
     * 群主将人踢出群
     *
     * @param userId
     * @param groupId
     * @param leaderId
     * @author Lixs
     * @Date 2017.7.11
     */
    @Transactional
    public int quitGroupByLeader(String leaderUserId, String userId, String groupId) {
        logger.info("小组创建者踢人出群");
        if (!StringUtils.hasText(userId)) {
            throw new AppException("群员id为空");
        }
        if (!StringUtils.hasText(leaderUserId)) {
            throw new AppException("群主id为空");
        }
        if (!StringUtils.hasText(groupId)) {
            throw new AppException("小组id为空");
        }
        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(groupId);
        if (forumgroup == null) {
            throw new AppException("未找到该小组的信息");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已经被解散");
        }
        if (!leaderUserId.equals(forumgroup.getLeaderUserId())) {
            throw new AppException("你不是群主，无法移除小组成员");
        }
        Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, groupId);
        if (forumuserinforumgroup == null) {
            throw new AppException("小组中不存在该用户");
        }
        if (forumgroup.getLeaderUserId().equals(userId)) {
            throw new AppException("无法移除群主 ");
        }

        //如果是邀请进群，则用户退群时删除用户的邀请记录
        Forumgroupinvitationrecord forumgroupinvitationrecord = forumgroupinvitationrecordMapper.selectByGroupIdAndUserId(userId, groupId);
        if (null != forumgroupinvitationrecord) {
            //删除用户的邀请记录
            forumgroupinvitationrecordMapper.deleteByPrimaryKey(forumgroupinvitationrecord.getGroupInvitationRecordId());
        }

        //如果该用户是通过申请加群，则退群时将申请记录的状态置为申请拒绝加群
        Forumuserapplyjoingrouprecord applyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, groupId);
        if (null != applyjoingrouprecord) {
            applyjoingrouprecord.setApplyStatus(ForumgroupStatic.not_in_group);
            forumuserapplyjoingrouprecordMapper.updateByPrimaryKeySelective(applyjoingrouprecord);

            //调用环信接口，移除单个群组成员
            friendsClient.deleteGroupUser(forumgroup.getHuanxinGroupId(), userId);
            //删除本地的群组与用户的关联记录
            forumuserinforumgroupMapper.deleteByUserIdAndGroupId(userId, groupId);

            List<Forumuserinforumgroup> forumuserinforumgroupnew = forumuserinforumgroupMapper.selectByGroupId(groupId);
            forumgroup.setMemberCount(forumuserinforumgroupnew.size());
            return forumgroupMapper.updateByPrimaryKey(forumgroup);
        }


        //调用环信，移除单个群组成员
        friendsClient.deleteGroupUser(forumgroup.getHuanxinGroupId(), userId);
        forumuserinforumgroupMapper.deleteByUserIdAndGroupId(userId, groupId);

        List<Forumuserinforumgroup> forumuserinforumgroupnew = forumuserinforumgroupMapper.selectByGroupId(groupId);
        forumgroup.setMemberCount(forumuserinforumgroupnew.size());
        return forumgroupMapper.updateByPrimaryKey(forumgroup);
    }

    /**
     * 通过组名模糊查询小组信息
     *
     * @param userId
     * @param groupName
     * @param currentPage
     * @param rows
     * @return
     */
    @Transactional
    public List<ForumInUserGroupVo> selectByGroupName(String userId, String groupName, Integer currentPage, Integer rows) {
        logger.info("通过组名查询小组信息");
        PageHelper.startPage(currentPage, rows);
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户id不能为空");
        }
        List<ForumInUserGroupVo> forumInUserGroupVo = forumgroupMapper.selectByGroupName(userId, groupName);
        if (forumInUserGroupVo == null) {
            throw new AppException("未查到相关小组信息");
        }
        return forumInUserGroupVo;
    }

    /**
     * 通过小组id来查询小组信息
     *
     * @param forumgroupId
     * @author lixs
     * @Date 2017.7.20
     */
    @Transactional
    public Forumgroup selectGroupById(String forumgroupId) {
        if (forumgroupId == null) {
            throw new AppException("小组id不能为空");
        }
        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
        if (forumgroup == null) {
            throw new AppException("不存在该小组");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已经被解散");
        }


        return forumgroup;
    }

    /**
     * 通过小组环信id来查询小组信息
     *
     * @param huanxinId
     * @author lixs
     * @Date 2017.7.20
     */
    @Transactional
    public Forumgroup selectGroupByHuanXinId(String huanxinId) {
        if (huanxinId == null) {
            throw new AppException("小组id不能为空");
        }
        Forumgroup forumgroup = forumgroupMapper.selectGroupDetailByHuanxin(huanxinId);
        if (forumgroup == null) {
            throw new AppException("不存在该小组");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已经被解散");
        }


        return forumgroup;
    }


    /**
     * 获取小组最新动态
     *
     * @param forumgroupId
     * @return
     */
    public Groupnotice getNewestGroupNotice(String forumgroupId) {
        Groupnotice groupnotice = groupnoticeMapper.selectNewestNotice(forumgroupId);
        return groupnotice;
    }


    /**
     * 多条件查询小组信息(后台页面)
     *
     * @param groupName
     * @param privacy
     * @param createDateS
     * @param createDateE
     * @author lixs
     * @Date 2017.7.25
     */
    @Transactional
    public List<Forumgroup> selectGroupByNameAndDateByPage(String groupName, Integer privacy, String createDateS, String createDateE, Integer currentPage, Integer rows) {
        logger.info("多条件查询小组信息");
        PageHelper.startPage(currentPage, rows);
        List<Forumgroup> forumgroup = forumgroupMapper.selectGroupByNameAndDate(groupName, privacy, createDateS, createDateE);
        if (forumgroup == null) {
            throw new AppException("未查到用户信息");
        }
        return forumgroup;
    }


    /**
     * 创建小组（系统小组）
     *
     * @param forumgroup
     * @author lixs
     * @Date 2017.7.26
     */
    @Transactional
    public Boolean saveSystemForumGroupBatch(List<BatchVo> forumgroup) {
        logger.info("saveForumGroup!");
        if (null == forumgroup) {
            throw new AppException("forumgroup参数为空！");
        }
        //调用环信接口，创建小组
        for (int index = 750; index < forumgroup.size(); index++) {
            logger.info("执行次数" + index + forumgroup.size());
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("groupname", forumgroup.get(index).getGroupName());
            resultMap.put("desc", "这是一个分享快乐的小组!");
            resultMap.put("public", true);
            //设置群最大人数（包含群主）
            resultMap.put("maxusers", maxusers);
            resultMap.put("members_only", false);
            //allowinvites 是否允许群成员邀请别人加入此群。 true：允许群成员邀请人加入此群
            resultMap.put("allowinvites", true);
            resultMap.put("owner", "16050746gorh94ir3273");
            resultMap.put("members", null);

            //解析环信返回的json
            String result = friendsClient.createGroupUser(resultMap).getData();
            HuanxinJson huanxinJson = GSON.fromJson(result, HuanxinJson.class);

            //创建小组
            Forumgroup forumgroupNew = new Forumgroup();
            forumgroupNew.setCreateDate(new Date());
            forumgroupNew.setMemberCount(1);
            forumgroupNew.setForumGroupId(StringUUIdUtil.getUUID());
            forumgroupNew.setPrivacySetting(ForumgroupStatic.privacy_public);
            forumgroupNew.setGroupName(forumgroup.get(index).getGroupName());
            forumgroupNew.setLeaderUserId("16050746gorh94ir3273");
            //小组创建者的昵称和头像是动态从用户表中获取。
            forumgroupNew.setLeaderUserNickname(userFeignClient.getUser("16050746gorh94ir3273").getData().getName());
            forumgroupNew.setLeaderUserHeadUrl(userFeignClient.getUser("16050746gorh94ir3273").getData().getImageUrl());
            forumgroupNew.setLongitude(exchange(forumgroup.get(index).getLongitude()));
            forumgroupNew.setLatitude(exchange(forumgroup.get(index).getLatitude()));
            forumgroupNew.setGroupIntroduction("这是一个快乐的小组");
            forumgroupNew.setHuanxinGroupId(huanxinJson.data.groupid);
            forumgroupNew.setAddress(forumgroup.get(index).getAddress());
            forumgroupNew.setGroupMessageTotal(0);
            //系统群的头像默认与背景图一致
            forumgroupNew.setHeadUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/165j3tb5jsiuhuxs680w.jpg");
            forumgroupNew.setGroupBackgroundUrl("http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/165j3tb5jsiuhuxs680w.jpg");
            forumgroupNew.setGroupType(ForumgroupStatic.forum_group_type_for_system);
//		forumgroupNew.setGroupNotice(userFeignClient.getUser("15zouzi90truhdk1fcmh").getData().getName()+"创建了小组"+forumgroup.get(index).getGroupName());
            forumgroupMapper.insertSelective(forumgroupNew);

            logger.info("创建本地小组成功次数" + index);
            logger.info("第" + index + "次群组的id" + forumgroupNew.getForumGroupId());
            //创建群主与小组的关联
            saveGroupAndLeaderRel(forumgroupNew, forumgroupNew.getLeaderUserId());
        }
        return true;
    }

    /**
     * 首页设置是否显示群成员帖
     *
     * @param forumgroupId
     * @param userId
     * @return
     */
    @Transactional
    public int updateGroupMessageSetting(String forumgroupId, String userId, Integer status) {
        if (!StringUtils.hasText(forumgroupId)) {
            throw new AppException("小组id不能为空");
        }
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户id不能为空");
        }
        if (status == null) {
            throw new AppException("是否显示群成员帖状态不能为空");
        }
        Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, forumgroupId);
        if (null == forumuserinforumgroup) {
            throw new AppException("未找到该用户与小组的关联记录");
        }
        forumuserinforumgroup.setUserGroupForumMessageSetting(status);
        return forumuserinforumgroupMapper.updateByPrimaryKeySelective(forumuserinforumgroup);
    }

    /**
     * 更改小组的背景图片
     *
     * @param forumgroupId
     * @param backGroundImg
     * @author lixs
     * @Date 2017.7.29
     */
    @Transactional
    public int UpdateGroupBackgroundImg(String forumgroupId, String backGroundImg, String leaderUserId) {
        if (!StringUtils.hasText(forumgroupId)) {
            throw new AppException("小组id不能为空");
        }
        if (!StringUtils.hasText(backGroundImg)) {
            throw new AppException("小组背景图片不能为空");
        }
        if (!StringUtils.hasText(leaderUserId)) {
            throw new AppException("群主id不能为空");
        }
        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
        if (null == forumgroup) {
            throw new AppException("小组信息为空");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已经被解散");
        }
        if (!leaderUserId.equals(forumgroup.getLeaderUserId())) {
            throw new AppException("你不是群主，无法更改群组背景图片");
        }
        forumgroup.setGroupBackgroundUrl(backGroundImg);
        return forumgroupMapper.updateByPrimaryKey(forumgroup);
    }


    /**
     * 获取用户列表（除去小组以外的用户）
     *
     * @param forumgroupId
     * @lixs
     * @Date 2017.7.31
     */
    public List<User> findFriends(String forumgroupId) {
        if (!StringUtils.hasText(forumgroupId)) {
            throw new AppException("小组id不能为空");
        }

        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
        if (null == forumgroup) {
            throw new AppException("不存在该小组");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已经被解散");
        }
        ResultMessage<List<User>> data = friendsClient.findFriends();
        List<User> friendsList = data.getData();
        List<User> users = new ArrayList<User>();
        List<Forumuserinforumgroup> forumuserinforumgroup = forumuserinforumgroupMapper.selectByGroupId(forumgroupId);
        if (null == forumuserinforumgroup) {
            throw new AppException("未能查到小组的相关关联记录");
        }
        for (User user : friendsList) {
            Forumuserinforumgroup forumuser = forumuserinforumgroupMapper.selectByUserIdAndGroupId(user.getUserId(), forumgroupId);
            if (null == forumuser) {
                users.add(user);
            }
        }
        return users;
    }

    /**
     * 获取小组详细信息，包含与用户关联的信息
     *
     * @param userId
     * @param forumgroupId
     * @author lixs
     * @Date 2017.7.31
     */
    public ForumgroupInUserVo findForumgroupDetails(String userId, String forumgroupId) {
        if (!StringUtils.hasText(forumgroupId)) {
            throw new AppException("群组id不能为空");
        }
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户id不能为空");
        }
        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
        if (null == forumgroup) {
            throw new AppException("该小组不存在");
        }

        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已经被解散");
        }
        //查出的是群组的基本信息
        ForumgroupInUserVo forumgroupInUserVo = forumgroupMapper.findForumgroupDetails(forumgroupId);
        if (null == forumgroupInUserVo) {
            throw new AppException("小组关联信息获取失败");
        }
        //如果用户是群成员，那么会另外查出用户对群的设置
        Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, forumgroupId);
        if (null != forumuserinforumgroup) {
            forumgroupInUserVo.setUserGroupChatSetting(forumuserinforumgroup.getUserGroupChatSetting());
            forumgroupInUserVo.setUserGroupForumMessageSetting(forumuserinforumgroup.getUserGroupForumMessageSetting());
            forumgroupInUserVo.setIsJoin(forumuserinforumgroup.getUserId());
        }
        //如果用户申请过加入该群，则会查出该用户的申请状态
        Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, forumgroupId);
        if (null != forumuserapplyjoingrouprecord) {
            forumgroupInUserVo.setApplyStatus(forumuserapplyjoingrouprecord.getApplyStatus());
        }

        if (userId.equals(forumgroup.getLeaderUserId())) {
            forumgroupInUserVo.setApplyStatus(ForumgroupStatic.apply_status_agree);
            forumgroupInUserVo.setIsJoin(forumgroup.getLeaderUserId());
        }

        return forumgroupInUserVo;
    }

    /**
     * 多条件查询小组信息
     *
     * @param groupName
     * @param leaderUserName
     * @param groupType
     * @param groupStyle
     * @param memberCountMin
     * @param memberCountMax
     * @param groupMessageTotalMin
     * @param groupMessageTotalMax
     * @param createDateS
     * @param createDateE
     * @param currentPage
     * @param rows
     * @author lixs
     * @Date 2017.8.3
     */
    public List<Forumgroup> selectForumgroup(String groupName, String leaderUserName, String groupType, String groupStyle,
                                             Integer memberCountMin, Integer memberCountMax, Integer groupMessageTotalMin,
                                             Integer groupMessageTotalMax, String createDateS, String createDateE, Integer currentPage,
                                             Integer rows) {
        PageHelper.startPage(currentPage, rows);
        List<Forumgroup> forumgroup = forumgroupMapper.selectForumgroup(groupName, leaderUserName, groupType, groupStyle,
                memberCountMin, memberCountMax, groupMessageTotalMin, groupMessageTotalMax, createDateS, createDateE);


        return forumgroup;
    }

    //根据用户id统计小组总数
    public int countGroupByUserId(String userId) {

        return forumgroupMapper.countGroupByUserId(userId, ForumgroupStatic.forum_group_type_for_delete);
    }

    //用来获取查询附近小组的分页数据的总数
    @Transactional
    public List<ForumInUserGroupVo> getNearByGroupsTotal(Double userLongitud, Double uerLatitude, Integer distance, String userId) {
        if (userLongitud == null) {
            throw new AppException("用户经度不能为空");
        }
        if (uerLatitude == null) {
            throw new AppException("用户纬度不能为空");
        }
        if (distance == null) {
            throw new AppException("用户设置的距离不能为空");
        }

        double ratio = Math.cos(uerLatitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;

        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude = userLongitud - longitudeDistance;
        Double maxLongitude = userLongitud + longitudeDistance;
        Double minLatitude = uerLatitude - latitudeDistance;
        Double maxLatitude = uerLatitude + latitudeDistance;
        return forumgroupMapper.selectNearbyGroups(minLongitude, maxLongitude, minLatitude, maxLatitude, userId, userLongitud, uerLatitude, distance, ForumgroupStatic.privacy_public);
    }


    //多条件查询的分页数据的总数
    public int countForumgroupTotal(String groupName, String leaderUserName, String groupType, String groupStyle,
                                    Integer memberCountMin, Integer memberCountMax, Integer groupMessageTotalMin,
                                    Integer groupMessageTotalMax, String createDateS, String createDateE) {

        return forumgroupMapper.countForumgroupTotal(groupName, leaderUserName, groupType, groupStyle,
                memberCountMin, memberCountMax, groupMessageTotalMin, groupMessageTotalMax, createDateS, createDateE);
    }


    //获取通过小组名查询小组的总数
    public int selectByGroupNameForTotal(String userId, String groupName) {
        return forumgroupMapper.selectByGroupNameForTotal(userId, groupName);
    }

    /**
     * 获取所有的群组个数
     *
     * @return int
     * @author lid
     * @date 2017.8.7
     */
    public int countAllGroups() {
        return forumgroupMapper.countAllGroups();
    }

    /**
     * 获取今天创建的群组个数
     */
    public int countTodayNewGroups() {
        Calendar cal = Calendar.getInstance();
        Date deadTime = new Date();
        cal.setTime(deadTime);

        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        deadTime = cal.getTime();
        Integer todayNewGroups = forumgroupMapper.countTodayNewGroups(deadTime);
        logger.info("todayNewGroups:" + todayNewGroups);
        return todayNewGroups;
    }

    //用户统计附近群组中未加入的群的总数
    @Transactional
    public int getNearByGroupsForOtherGroupTotal(Double userLongitud, Double userLatitude, Integer distance, String userId) {

        if (userLongitud == null) {
            throw new AppException("用户经度不能为空");
        }
        if (userLatitude == null) {
            throw new AppException("用户纬度不能为空");
        }
        if (distance == null) {
            throw new AppException("用户设置的距离不能为空");
        }

        ResultMessage<FocusRegion> focusRegion = userFeignClient.checkedFocusRegion();
        if (null == focusRegion.getData()) {
            double ratio = Math.cos(userLatitude * 0.017453292519943295);
            double latitudeDistance = distance * 0.000008998200359928014;

            // 以纬度为标准 纬度换算成等效经度距离
            double longitudeDistance = latitudeDistance / ratio;
            Double minLongitude = userLongitud - longitudeDistance;
            Double maxLongitude = userLongitud + longitudeDistance;
            Double minLatitude = userLatitude - latitudeDistance;
            Double maxLatitude = userLatitude + latitudeDistance;
            return forumgroupMapper.getNearByGroupsForOtherGroupForTotal(minLongitude, maxLongitude, minLatitude, maxLatitude, userId, userLongitud, userLatitude, distance, ForumgroupStatic.privacy_public);
        }
        logger.info("关注区域不为空");
        Double latitude = focusRegion.getData().getLatitude();
        Double longitud = focusRegion.getData().getLongitude();

        double ratio = Math.cos(latitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;

        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude = longitud - longitudeDistance;
        Double maxLongitude = longitud + longitudeDistance;
        Double minLatitude = latitude - latitudeDistance;
        Double maxLatitude = latitude + latitudeDistance;
        return forumgroupMapper.getNearByGroupsForOtherGroupForTotal(minLongitude, maxLongitude, minLatitude, maxLatitude, userId, longitud, latitude, distance, ForumgroupStatic.privacy_public);


    }

    /**
     * 群聊消息免打扰
     *
     * @param userId
     * @param groupId
     * @param status
     * @author lixs
     * @Date 2017.8.8
     */
    @Transactional
    public int updateGroupChatSetting(String userId, String groupId, Integer status) {
        if (!StringUtils.hasText(groupId)) {
            throw new AppException("小组id不能为空");
        }
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户id不能为空");
        }
        if (status == null) {
            throw new AppException("群聊消息免打扰状态不能为空");
        }
        Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, groupId);
        if (null == forumuserinforumgroup) {
            throw new AppException("未查到用户与小组的记录");
        }
        forumuserinforumgroup.setUserGroupChatSetting(status);
        return forumuserinforumgroupMapper.updateByPrimaryKeySelective(forumuserinforumgroup);
    }

    /**
     * 获取群聊消息免打扰的小组id
     *
     * @param userId
     * @author lixs
     * @Date 2017.8.8
     */
    @Transactional
    public List<String> selectForumgroupIdByChatSetting(String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户id不能为空");
        }
        List<Forumuserinforumgroup> forumuserinforumgroup = forumuserinforumgroupMapper.selectForumgroupIdByChatSetting(userId);
        if (null == forumuserinforumgroup) {
            throw new AppException("用户与小组的关联记录为空");
        }
        List<String> forumgroupId = new ArrayList<String>();
        for (int index = 0; index < forumuserinforumgroup.size(); index++) {
            forumgroupId.add(forumuserinforumgroup.get(index).getForumGroupId());
        }
        return forumgroupId;
    }

    /**
     * 筛选出用户未加入群的列表
     *
     * @param userLongitud
     * @param uerLatitude
     * @param distance
     * @param userId
     * @param currentPage
     * @param rows
     * @author lixs
     * @Date 2017.8.9
     */
    @Transactional
    public List<ForumInUserGroupVo> getNearByGroupsForOtherGroup(Double userLongitud, Double userLatitude, Integer distance, String userId, Integer currentPage, Integer rows) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户id不能为空");
        }
        if (userLongitud == null) {
            throw new AppException("用户经度不能为空");
        }
        if (userLatitude == null) {
            throw new AppException("用户纬度不能为空");
        }
        if (distance == null) {
            throw new AppException("用户设置的距离不能为空");
        }

        PageHelper.startPage(currentPage, rows);
        ResultMessage<FocusRegion> focusRegion = userFeignClient.checkedFocusRegion();

        Double latitude;
        Double longitud;

        if (null == focusRegion.getData()) {
            logger.info("关注区域为空");

            //使用用户传递的经纬度
            latitude = userLatitude;
            longitud = userLongitud;
        } else {
            logger.info("关注区域不为空");

            //使用用户关注的区域经纬度
            latitude = focusRegion.getData().getLatitude();
            longitud = focusRegion.getData().getLongitude();
        }


        double ratio = Math.cos(latitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;
        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;

        Double minLongitude = longitud - longitudeDistance;
        Double maxLongitude = longitud + longitudeDistance;
        Double minLatitude = latitude - latitudeDistance;
        Double maxLatitude = latitude + latitudeDistance;

        List<ForumInUserGroupVo> nearGroupList = forumgroupMapper.getNearByGroupsForOtherGroup(minLongitude, maxLongitude, minLatitude, maxLatitude, userId, longitud, latitude, distance, ForumgroupStatic.privacy_public);

        //避免由于四舍五入，导致计算出来的距离大于用户给定的距离
        for (ForumInUserGroupVo groupVo : nearGroupList) {
            try {
                Integer resultDistance = Integer.valueOf(groupVo.getDistance());
                if (resultDistance > distance) {
                    logger.info("附近群组距离测算距离大于用户给定的距离，测算出来的：" + resultDistance
                            + " 用户给的：" + distance);
                    groupVo.setDistance(String.valueOf(distance));
                }

            } catch (Exception e) {
                logger.error("附近群组距离测算异常" + e.toString());
            }
        }

        return nearGroupList;
    }

    /**
     * 创建系统群组
     *
     * @param forumgroup
     * @author lixs
     * @Date 2017.12.13
     */
    @Transactional
    public int saveSystemForumGroup(Forumgroup forumgroup) {
        logger.info("saveForumGroup!");
        //群组信息判空
        groupDetailJudgement(forumgroup);

        if (!StringUtils.hasText(forumgroup.getGroupIntroduction())) {
            throw new AppException("群组介绍不能为空");
        }

        //调用环信接口，创建小组
        logger.info("是否执行到这里");
        HuanxinJson huanxinJson = createHuanxinGroup(forumgroup, null, true, false);

        //创建系统小组
        logger.info("创建系统小组");
        Forumgroup forumgroupNew = createGroup(forumgroup, null, huanxinJson, forumgroup.getGroupIntroduction(),
                forumgroup.getGroupStyle(), ForumgroupStatic.forum_group_type_for_system,
                ForumgroupStatic.privacy_public);

        //创建群主与小组的关联
        saveGroupAndLeaderRel(forumgroupNew, forumgroupNew.getLeaderUserId());
        return 1;
    }

    /**
     * 群组信息判空
     *
     * @param forumgroup
     * @author lixs
     * @date 2017.12.13
     */
    public void groupDetailJudgement(Forumgroup forumgroup) {
        if (null == forumgroup) {
            throw new AppException("forumgroup参数为空！");
        }
        if (!StringUtils.hasText(forumgroup.getGroupName())) {
            throw new AppException("小组名称不能为空");
        }
        if (forumgroup.getGroupName().length() > 15) {
            throw new AppException("小组名称长度不能超过15个字符");
        }
        if (!StringUtils.hasText(forumgroup.getLeaderUserId())) {
            throw new AppException("群主的id不能为空");
        }
    }

    @Transactional
    public int selectGroupByNameAndDateForTotal(String groupName, Integer privacy, String createDateS, String createDateE) {
        return forumgroupMapper.selectGroupByNameAndDateForTotal(groupName, privacy, createDateS, createDateE);
    }

    @Transactional
    public List<Forumgroup> selectGroupAndUserDetailBatch(List<String> huanxinGroupId) {
        if (null == huanxinGroupId) {
            return null;
        }

        List<Forumgroup> forumgroups = new ArrayList<Forumgroup>();
        for (int index = 0; index < huanxinGroupId.size(); index++) {
            Forumgroup forumgroup = forumgroupMapper.selectGroupDetailByHuanxin(huanxinGroupId.get(index));
            if (null != forumgroup && !forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
                forumgroups.add(forumgroup);
            }

        }

        return forumgroups;
    }

    /**
     * 批量删除公开群
     *
     * @author lixs
     * @Date 2017.8.19
     */
    @Transactional
    public int deleteGroupForSystemBatch() {
        List<Forumgroup> forumgroup = forumgroupMapper.selectGroupIdForSystem();
        for (int index = 0; index < forumgroup.size(); index++) {
            //删除小组与用户的关联信息
            forumuserinforumgroupMapper.deleteByForumgroupId(forumgroup.get(index).getForumGroupId());
            //物理删除群组
            forumgroupMapper.deleteByPrimaryKey(forumgroup.get(index).getForumGroupId());
            //删除环信小组的信息
            friendsClient.deleteGroup(forumgroup.get(index).getHuanxinGroupId());
        }
        return -1;
    }

    /**
     * 通过环信id获取小组详细信息，包含与用户关联的信息
     *
     * @param userId
     * @param huanxinId
     * @author lixs
     * @Date 2017.8.25
     */
    public ForumgroupInUserVo findForumgroupDetailsByHuanxinId(String userId, String huanxinId) {
        if (!StringUtils.hasText(huanxinId)) {
            throw new AppException("群组id不能为空");
        }
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户id不能为空");
        }
        Forumgroup forumgroup = forumgroupMapper.selectGroupDetailByHuanxin(huanxinId);
        if (null == forumgroup) {
            throw new AppException("该小组不存在");
        }

        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已经被解散");
        }
        //查出的是群组的基本信息
        ForumgroupInUserVo forumgroupInUserVo = forumgroupMapper.findForumgroupDetails(forumgroup.getForumGroupId());
        if (null == forumgroupInUserVo) {
            throw new AppException("小组关联信息获取失败");
        }
        //如果用户是群成员，那么会另外查出用户对群的设置
        Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, forumgroup.getForumGroupId());
        if (null != forumuserinforumgroup) {
            forumgroupInUserVo.setUserGroupChatSetting(forumuserinforumgroup.getUserGroupChatSetting());
            forumgroupInUserVo.setUserGroupForumMessageSetting(forumuserinforumgroup.getUserGroupForumMessageSetting());
            forumgroupInUserVo.setIsJoin(forumuserinforumgroup.getUserId());
        }
        //如果用户申请过加入该群，则会查出该用户的申请状态
        Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, forumgroup.getForumGroupId());
        if (null != forumuserapplyjoingrouprecord) {
            forumgroupInUserVo.setApplyStatus(forumuserapplyjoingrouprecord.getApplyStatus());
        }

        if (userId.equals(forumgroup.getLeaderUserId())) {
            forumgroupInUserVo.setApplyStatus(ForumgroupStatic.apply_status_agree);
            forumgroupInUserVo.setIsJoin(forumgroup.getLeaderUserId());
        }
        return forumgroupInUserVo;
    }

    /**
     * 删除单个小组，逻辑删除(慎用)
     *
     * @param forumgroupId
     * @author lixs
     * @Date 2017.10.19
     */
    @Transactional
    public int deleteForumgroup(String forumgroupId) {
        if (!StringUtils.hasText(forumgroupId)) {
            throw new AppException("您未选中任何小组");
        }
        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupId);
        if (null == forumgroup) {
            throw new AppException("该小组不存在");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已被解散，无法继续删除");
        }
        //删除小组与用户的关联记录
        forumuserinforumgroupMapper.deleteByForumgroupId(forumgroupId);

        //调用环信接口：解散群组
        friendsClient.deleteGroup(forumgroup.getHuanxinGroupId());
        logger.info("解散小组");
        forumgroup.setGroupType(ForumgroupStatic.forum_group_type_for_delete);
        forumgroup.setMemberCount(0);
        return forumgroupMapper.updateByPrimaryKey(forumgroup);
    }

    //double类型的数据保存后六位并且四舍五入
    public Double exchange(Double num) {
        if (null == num) {
            return num;
        }
        BigDecimal param = new BigDecimal(num);
        Double result = param.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        return result;
    }

    /*	*//**
     * 导出excel
     * @param reponse
     *//*
	public void export(HttpServletResponse reponse){
	//创建HSSFWorkbook对象(excel的文档对象)
    HSSFWorkbook wb = new HSSFWorkbook();
	//建立新的sheet对象（excel的表单）
	HSSFSheet sheet=wb.createSheet("群组表");
	//在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
	HSSFRow row1=sheet.createRow(0);
	//创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
	HSSFCell cell=row1.createCell(0);
	//设置单元格内容
	cell.setCellValue("学员考试成绩一览表");
	//合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
	sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
	//在sheet里创建第二行
	HSSFRow row2=sheet.createRow(1);    
	      //创建单元格并设置单元格内容
	      row2.createCell(0).setCellValue("姓名");
	      row2.createCell(1).setCellValue("班级");    
	      row2.createCell(2).setCellValue("笔试成绩");
	      row2.createCell(3).setCellValue("机试成绩");    
	      //在sheet里创建第三行
	      HSSFRow row3=sheet.createRow(2);
	      row3.createCell(0).setCellValue("李明");
	      row3.createCell(1).setCellValue("As178");
	      row3.createCell(2).setCellValue(87);    
	      row3.createCell(3).setCellValue(78);    
	  //.....省略部分代码


	//输出Excel文件
	    OutputStream output;
		try {
			output = reponse.getOutputStream();
			 reponse.reset();
			    reponse.setHeader("Content-disposition", "attachment; filename=details.xls");
			    reponse.setContentType("application/msexcel");        
			    wb.write(output);
			    output.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   
	}*/

}

